import Router from '@koa/router'
import { z } from 'zod'
import { prisma } from '../../app'
import { createError } from '../../middleware/errorHandler'

const router = new Router()

// 验证 schema
const getCommentsQuerySchema = z.object({
    postId: z.string().min(1, 'Post ID is required'),
    page: z.string().optional().transform(val => val ? parseInt(val) : 1),
    limit: z.string().optional().transform(val => val ? parseInt(val) : 10)
})

const createCommentSchema = z.object({
    content: z.string().min(1, 'Content is required').max(1000, 'Content must be at most 1000 characters'),
    postId: z.string().min(1, 'Post ID is required'),
    parentId: z.string().optional()
})

const updateCommentSchema = z.object({
    content: z.string().min(1, 'Content is required').max(1000, 'Content must be at most 1000 characters')
})

const getCommentByIdSchema = z.object({
    id: z.string().min(1, 'Comment ID is required')
})

// 获取评论列表
router.get('/', async (ctx) => {
    try {
        const query = getCommentsQuerySchema.parse(ctx.query)
        const { postId, page, limit } = query

        const skip = (page - 1) * limit

        // 验证文章是否存在
        const post = await prisma.post.findUnique({
            where: { id: postId },
            select: { id: true }
        })

        if (!post) {
            throw createError.notFound('Post not found')
        }

        // 获取评论总数（只计算顶级评论）
        const total = await prisma.comment.count({
            where: {
                postId,
                parentId: null
            }
        })

        // 获取评论列表（只获取顶级评论，包含回复）
        const comments = await prisma.comment.findMany({
            where: {
                postId,
                parentId: null
            },
            skip,
            take: limit,
            include: {
                author: {
                    select: {
                        id: true,
                        username: true,
                        nickname: true,
                        avatar: true
                    }
                },
                replies: {
                    include: {
                        author: {
                            select: {
                                id: true,
                                username: true,
                                nickname: true,
                                avatar: true
                            }
                        }
                    },
                    orderBy: {
                        createdAt: 'asc'
                    }
                }
            },
            orderBy: {
                createdAt: 'desc'
            }
        })

        ctx.body = {
            success: true,
            message: 'Comments retrieved successfully',
            data: {
                comments,
                pagination: {
                    page,
                    limit,
                    total,
                    totalPages: Math.ceil(total / limit),
                    hasNext: page * limit < total,
                    hasPrev: page > 1
                }
            }
        }
    } catch (error) {
        throw error
    }
})

// 根据ID获取评论详情
router.get('/:id', async (ctx) => {
    try {
        const { id } = getCommentByIdSchema.parse(ctx.params)

        const comment = await prisma.comment.findUnique({
            where: { id },
            include: {
                author: {
                    select: {
                        id: true,
                        username: true,
                        nickname: true,
                        avatar: true
                    }
                },
                post: {
                    select: {
                        id: true,
                        title: true
                    }
                },
                parent: {
                    select: {
                        id: true,
                        content: true,
                        author: {
                            select: {
                                id: true,
                                username: true,
                                nickname: true
                            }
                        }
                    }
                },
                replies: {
                    include: {
                        author: {
                            select: {
                                id: true,
                                username: true,
                                nickname: true,
                                avatar: true
                            }
                        }
                    },
                    orderBy: {
                        createdAt: 'asc'
                    }
                }
            }
        })

        if (!comment) {
            throw createError.notFound('Comment not found')
        }

        ctx.body = {
            success: true,
            message: 'Comment retrieved successfully',
            data: comment
        }
    } catch (error) {
        throw error
    }
})

// 创建评论（需要认证）
router.post('/', async (ctx) => {
    try {
        if (!ctx.user) {
            throw createError.unauthorized('User not authenticated')
        }

        const commentData = createCommentSchema.parse(ctx.request.body)
        const { postId, parentId, content } = commentData

        // 验证文章是否存在
        const post = await prisma.post.findUnique({
            where: { id: postId },
            select: { id: true, status: true }
        })

        if (!post) {
            throw createError.notFound('Post not found')
        }

        if (post.status !== 'PUBLISHED') {
            throw createError.badRequest('Cannot comment on unpublished post')
        }

        // 如果是回复评论，验证父评论是否存在
        if (parentId) {
            const parentComment = await prisma.comment.findUnique({
                where: { id: parentId },
                select: { id: true, postId: true }
            })

            if (!parentComment) {
                throw createError.notFound('Parent comment not found')
            }

            if (parentComment.postId !== postId) {
                throw createError.badRequest('Parent comment does not belong to this post')
            }
        }

        const comment = await prisma.comment.create({
            data: {
                content,
                postId,
                parentId,
                authorId: ctx.user.userId
            },
            include: {
                author: {
                    select: {
                        id: true,
                        username: true,
                        nickname: true,
                        avatar: true
                    }
                },
                post: {
                    select: {
                        id: true,
                        title: true
                    }
                },
                parent: parentId ? {
                    select: {
                        id: true,
                        content: true,
                        author: {
                            select: {
                                id: true,
                                username: true,
                                nickname: true
                            }
                        }
                    }
                } : undefined
            }
        })

        ctx.body = {
            success: true,
            message: 'Comment created successfully',
            data: comment
        }
    } catch (error) {
        throw error
    }
})

// 更新评论（需要认证）
router.put('/:id', async (ctx) => {
    try {
        if (!ctx.user) {
            throw createError.unauthorized('User not authenticated')
        }

        const { id } = getCommentByIdSchema.parse(ctx.params)
        const { content } = updateCommentSchema.parse(ctx.request.body)

        // 检查评论是否存在且属于当前用户
        const existingComment = await prisma.comment.findUnique({
            where: { id },
            select: {
                id: true,
                authorId: true
            }
        })

        if (!existingComment) {
            throw createError.notFound('Comment not found')
        }

        if (existingComment.authorId !== ctx.user.userId) {
            throw createError.forbidden('You can only update your own comments')
        }

        const comment = await prisma.comment.update({
            where: { id },
            data: { content },
            include: {
                author: {
                    select: {
                        id: true,
                        username: true,
                        nickname: true,
                        avatar: true
                    }
                }
            }
        })

        ctx.body = {
            success: true,
            message: 'Comment updated successfully',
            data: comment
        }
    } catch (error) {
        throw error
    }
})

export default router
